'use strict'
import NProgress from '@/utils/nprogress' // progress bar
import { notification } from 'ant-design-vue'

/**
 * 一般错误信息
 */
export const serverCodeMessage = {
  200: '服务器成功返回请求的数据',
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Forbidden',
  404: 'Not Found',
  500: '服务器发生错误，请检查服务器(Internal Server Error)',
  502: '网关错误(Bad Gateway)',
  503: '服务不可用，服务器暂时过载或维护(Service Unavailable)',
  504: '网关超时(Gateway Timeout)',
}

/**
 * 异常处理程序
 */
export const errorHandler = (error) => {
  NProgress.done()
  const { response, errorType } = error
  // console.log(response);
  const { status, request, data, statusText } = response
  const { code, message } = data

  if (errorType === 'CustomError') {
    // 自定义错误
    notification['error']({
      message: `请求错误 ${code}: ${request.responseURL}`,
      description: message || statusText || 'Error',
    })
  } else if (response && response.status) {
    notification['error']({
      message: `请求错误 ${status}: ${request.responseURL}`,
      description: message || statusText || serverCodeMessage[response.status] || 'Error',
    })
  } else if (!response) {
    notification['error']({
      message: '网络异常',
      description: '您的网络发生异常，无法连接服务器',
    })
  }

  return Promise.reject(error)
}
